package ink.lovejinhu.leetcode;

import org.junit.Test;

/**
 * @author jinhu
 * created 2021-05-06 17:12
 */
public class Solution_0067 {
    public String addBinary(String a, String b) {
        if (a.length() == 0) {
            return b;
        }
        if (b.length() == 0) {
            return a;
        }
        char[] achar = a.toCharArray();
        char[] bchar = b.toCharArray();
        int max = Math.max(achar.length, bchar.length);
        int[] aint = new int[max];
        int[] bint = new int[max];
        int j = max - 1;
        for (int i = achar.length - 1; i >= 0; i--) {
            if (achar[i] == '1') {
                aint[j] = 1;
                j--;
            } else {
                aint[j] = 0;
                j--;
            }
        }
        int h = max - 1;
        for (int i = bchar.length - 1; i >= 0; i--) {
            if (bchar[i] == '1') {
                bint[h] = 1;
                h--;
            } else {
                bint[h] = 0;
                h--;
            }
        }
        int flag = 0;
        int[] result = new int[max];
        String s = "";
        for (int i = max - 1; i >= 0; i--) {
            int temp = bint[i] + aint[i] + flag;
            if (temp >= 2) {
                result[i] = temp - 2;
                flag = 1;
            } else {
                result[i] = temp;
                flag = 0;
            }
        }
        for (int i = 0; i < max; i++) {
            s = s + result[i];
        }

        if (flag == 1) {
            return flag + s;
        } else {
            return s;
        }
    }

    @Test
    public void test() {
        String a = "1010", b = "1011";
        String s = this.addBinary(a, b);
        System.out.println(s);


    }
}
